//
//  ViewController.swift
//  ljy_demo
//
//  Created by xiandao on 2025/9/3.
//

import UIKit
import Flutter

class ViewController: UIViewController {
    var flutterVC: FlutterViewController?
    
    var total: Int = 11110

    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Make a button to call the showFlutter function when pressed.
        let button = UIButton(type:UIButton.ButtonType.custom)
        button.addTarget(self, action: #selector(showFlutter), for: .touchUpInside)
        button.setTitle("Show Flutter!", for: UIControl.State.normal)
        button.frame = CGRect(x: 80.0, y: 210.0, width: 160.0, height: 40.0)
        button.backgroundColor = UIColor.blue
        self.view.addSubview(button)
        
        
        let add = UIButton(type:UIButton.ButtonType.custom)
        add.addTarget(self, action: #selector(addButtonAction), for: .touchUpInside)
        add.setTitle("add", for: UIControl.State.normal)
        add.frame = CGRect(x: 80.0, y: 310.0, width: 160.0, height: 40.0)
        add.backgroundColor = UIColor.blue
        self.view.addSubview(add)
    }

    @objc func showFlutter() {
//        if let flutterVC = flutterVC {
//            present(flutterVC, animated: true, completion: nil)
//        } else {
//            let flutterEngine = (UIApplication.shared.delegate as! AppDelegate).flutterEngine
//            let flutterViewController = FlutterViewController(engine: flutterEngine, nibName: nil, bundle: nil)
//            self.flutterVC = flutterViewController
//            present(flutterViewController, animated: true, completion: nil)
//        }
    }
    
    @objc func addButtonAction() {
        total += 10
        
        var dict = [String: Any]()
        dict.updateValue(total, forKey: "number")
        dict.updateValue("仙道是最棒的", forKey: "massage")
        dict.updateValue(true, forKey: "isTrue")
        
        if let chanel = homeFlutterChannel {
            chanel.invokeMethod("addReguments", arguments: self.dictToString(dict))
        }
    }
    
    // 字典转json
    func dictToString(_ dic:[String : Any]) -> String {
        let data = try? JSONSerialization.data(withJSONObject: dic, options: [])
        let str = String(data: data!, encoding: String.Encoding.utf8)
        return str! as String
    }
}

